@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

REM Parameters:
REM 1) flag (e.g., Chord_test_CRL_0.1.3_)
REM 2) apkPathOrDir (APK file path or directory)
REM 3) ver_desc optional, change log (defaults to flag)
REM 4) downloadUrl optional, download url (defaults to flag)

set "flag=%~1"
set "apkArg=%~2"
set "changeLog=%~3"
set "downloadUrl=%~4"

if "%flag%"=="" goto :usage
if "%apkArg%"=="" goto :usage
goto :args_ok

:usage
echo Usage: %~nx0  ^<flag^> ^<apkPathOrDir^> [ver_desc]
echo Example (dir): %~nx0 Chord_test_CRL_0.1.3_ C:\mateurp_pipline\mate-client-adnroid\app\build\outputs\apk\Release
echo Example (file): %~nx0 Chord_test_CRL_0.1.3_ C:\path\to\your.apk
echo Example (with desc): %~nx0 Chord_test_CRL_0.1.3_ C:\path\to\your.apk "Fix crash"
exit /b 1

:args_ok

if "%changeLog%"=="" set "changeLog=%flag%"

REM Generate timestamp (pure cmd, no PowerShell)
set "timestamp="
for /f "tokens=2 delims==." %%i in ('wmic os get LocalDateTime /value ^| findstr "="') do set "ldt=%%i"
set "timestamp=!ldt:~0,12!"
if "!timestamp!"=="" (
  set "timestamp=%date:~-4%%date:~5,2%%date:~8,2%%time:~0,2%%time:~3,2%"
  set "timestamp=%timestamp: =0%"
)
REM destDir will be derived from apkArg (file's parent or the directory itself)

REM Resolve APK: if file passed use it; otherwise pick latest from directory
set "sourceApk="
set "destDir="
if exist "%apkArg%" (
  for %%F in ("%apkArg%") do (
    set "ext=%%~xF"
    if /I "%%~xF"==".apk" (
      set "sourceApk=%apkArg%"
      set "destDir=%%~dpF"
    )
  )
)
if not defined sourceApk (
  if not exist "%apkArg%" (
    echo Path not found: %apkArg% 1>&2
    exit /b 1
  )
  set "apkDir=%apkArg%"
  set "latestApk="
  for /f "delims=" %%F in ('dir /b /a-d /o-d "%apkDir%\*.apk" 2^>nul') do (
    if not defined latestApk set "latestApk=%apkDir%\%%F"
  )
  if not defined latestApk (
    echo No APK found in directory: %apkDir% 1>&2
    exit /b 1
  )
  set "sourceApk=%latestApk%"
  set "destDir=%apkDir%"
)

set "destApkName=%flag%%timestamp%.apk"
set "joiner=\\"
if "%destDir:~-1%"=="\\" set "joiner="
set "destApkPath=%destDir%%joiner%%destApkName%"
copy /Y "%sourceApk%" "%destApkPath%" >nul

echo APK copied and renamed: %destApkPath%

REM Upload APK via curl to app store API
set "uploadUrl=http://appstore-admin.etouch.cn/app-store-server/api/app/pkg/latest/upload"
set "respFile=%destDir%\upload_resp_%timestamp%.txt"
echo Uploading to: %uploadUrl%
curl.exe --location --request POST "%uploadUrl%" ^
  --header "Content-Type: multipart/form-data" ^
  --form "file=@%destApkPath%" ^
  --form "ver_desc=%changeLog%" > "%respFile%" 2>&1
  
 echo "%destApkPath%" "%changeLog%" > "%respFile%" 2>&1

if errorlevel 1 (
  echo curl upload failed 1>&2
  type "%respFile%"
  exit /b 1
)
echo Server response saved to: %respFile%

REM 钉钉通知（通过 curl 发送 JSON，无需 PowerShell）
set "dingUrl=https://oapi.dingtalk.com/robot/send?access_token=63f44c11b75347b9e9bb48cb0d1ad1326ff2ffb671366091ea3cd827b44272a9"
set "dingBody=%destDir%\dingtalk_%timestamp%.json"
set "dingResp=%destDir%\dingtalk_resp_%timestamp%.txt"
REM 请确保 downloadUrl 变量已在脚本前面定义
> "%dingBody%" echo {"msgtype":"text","text":{"content":"安卓打包上传：%downloadUrl%%destApkName%"}}
curl.exe -s -H "Content-Type: application/json" -X POST --data "@%dingBody%" "%dingUrl%" > "%dingResp%" 2>&1

if errorlevel 1 echo DingTalk notification failed

echo END Upload APK

endlocal
exit /b 0